/**
 * 海报服务
 * 生成活动海报，并做缓存
 * 创建人： andyliwr
 * 时间： 2019年12月20日
 */

import puppeteer from 'puppeteer';
import path from 'path';
import os from 'os';
import fs from 'fs';
import uuid from 'uuid';
import delay from 'delay';
import download from 'download';
import { createCanvas, registerFont, loadImage } from 'canvas';
import uploadToTencentCos from './txCosUpload';
import redis from './redis';
import { PORT } from '../config';
import { Book } from '../models';

/**
 * 生成图片
 * @param url 差异网页地址
 * @param options 截图参数
 */
export async function screenshot(url, options) {
  // eslint-disable-next-line
  const newOptions = {
    ...options,
    width: 1000,
    height: 'auto'
  };
  const defaultPuppeteerOptions = {
    args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage'],
    devtools: false,
    headless: true,
    ignoreHTTPSErrors: true,
    slowMo: 0
  };

  // const defaultViewport = {
  //   deviceScaleFactor: 1,
  //   hasTouch: false,
  //   height: 1024,
  //   isLandscape: false,
  //   isMobile: false,
  //   width: newOptions.width
  // };
  const browser = await puppeteer.launch({ ...defaultPuppeteerOptions });
  try {
    const page = await browser.newPage();
    await page.goto(url, { timeout: 3000000 });
    const element = await page.$('.container');
    const id = uuid.v1();
    // 等待图片加载完毕
    await delay(1000);
    // 图片保存至本地
    const tmpUrl = path.join(os.tmpdir(), `${id}.png`);
    element &&
      (await element.screenshot({
        path: tmpUrl
      }));
    // 将图片上传至腾讯云
    const imgUrl = await uploadToTencentCos({
      Bucket: 'picture',
      Body: Buffer.from(fs.readFileSync(tmpUrl)),
      Type: 'buffer',
      Key: `mbook/poster/${id}.png`,
      useCdn: true
    });
    await browser.close();
    return imgUrl;
  } catch (err) {
    console.log(err);
    await browser.close();
    return null;
  }
}

/**
 * 生成书籍分享海报
 */
export async function makeBookPoster(bookid) {
  if (!bookid) {
    return '';
  }
  // 检查redis是否存在缓存
  const redisValue = await redis.get(`poster_book_${bookid}`);
  if (redisValue) {
    return redisValue;
  } else {
    // 需要重新生成
    const url = await screenshot(`http://localhost:${PORT}/api/front/poster/book_preview?id=${bookid}`, { width: 604, height: 'auto' });
    // 海报缓存12小时
    redis.set(`poster_book_${bookid}`, url, 'EX', 60 * 60 * 12);
    return url;
  }
}

/**
 * 生成书籍简介
 * 使用 node canvas 技术
 */
const DEFAULT_IMG = 'https://picture-1256514897.file.myqcloud.com/book/images/share-mp-weixin.png'; // 默认图片
registerFont(path.join(__dirname, '../public/fonts/SongTi.ttf'), { family: '宋体' }); // 注册字体

export async function makeBookIntro(bookid) {
  if (!bookid) {
    return DEFAULT_IMG;
  }
  const thisBook = await Book.findById(bookid);
  if (!thisBook) return DEFAULT_IMG;
  const canvas = createCanvas(300, 240); // 按照微信官方要求，长宽比5:4
  const context = canvas.getContext('2d');
  context.font = '14px "宋体"'; // 统一使用微软雅黑字体
  context.fillStyle = 'rgb(255, 255, 255)';
  context.fillRect(0, 0, 300, 240);

  const imgBuf = await download(thisBook.img_url);
  const factionImg = await loadImage(imgBuf);
  context.drawImage(factionImg, 12, 12, 60, 96);
  context.textAlign = 'left';
  context.font = 'bold 16px 宋体';
  context.fillStyle = 'rgb(0, 0, 0)';
  context.fillText(thisBook.name, 84, 24, 204);
  context.font = 'normal 12px 宋体"';
  context.fillText(`作者：${thisBook.author}`, 84, 49, 204);
  context.fillText(`分类：${thisBook.classify.join('、') || '暂无'}`, 84, 74, 204);
  context.fillText(`状态：${thisBook.update_status || '暂无'}`, 84, 99, 204);
  context.fillText(`字数：${thisBook.total_words || '暂无'}`, 84, 124, 204);
  context.fillText(`最新章节：${`第${thisBook.newest_chapter}章`}`, 84, 149, 204);
  const noSpaceContent = `简介：${thisBook.des}`.replace(/(\n|\t|\r)/g, '');
  const oneTextWidth = context.measureText('测').width;
  const oneLineMaxTextNumber = Math.ceil(204 / oneTextWidth);
  // 小说描述最大行数
  let maxLineNumber = 4;
  let current = 4;
  while (current > 0) {
    let tmpText = noSpaceContent.substring(oneLineMaxTextNumber * (maxLineNumber - current), oneLineMaxTextNumber * (maxLineNumber + 1 - current));
    // 最后一行文字显示省略号
    if (current === 1) {
      tmpText = tmpText.substring(0, tmpText.length - 2) + '...';
    }
    context.fillText(tmpText, 84, 174 + (maxLineNumber - current) * 15, 204);
    current--;
  }

  const id = uuid.v1();
  const url = await uploadToTencentCos({
    Bucket: 'picture',
    Body: canvas.toBuffer(),
    Type: 'buffer',
    Key: `mbook/book-info/${id}.png`,
    useCdn: true
  });

  return url;
}

// (async function () {
//   const img = await makeBookIntro('5b13ed1491883d2704fd847b');
// })();
